var coord2addr =
    {
	apikey: "459c244ff059e0d3a7fc6b0d1e7b3127edec7423",
	init : function()
	{
	},

	pingSearch : function(lat, lng)
	{
	    if (lat && lng)
	    {
		coord2addr.s = document.createElement('script');
		coord2addr.s.type ='text/javascript';
		coord2addr.s.charset ='utf-8';
		coord2addr.s.src = 'http://apis.daum.net/maps/coord2addr?apikey=' + coord2addr.apikey +
		    '&output=json&format=simple&callback=coord2addr.pongSearch&inputCoordSystem=WGS84&latitude=' + lat + '&longitude=' + lng;
		document.getElementsByTagName('head')[0].appendChild(coord2addr.s);
	    }
	},
	// 검색 결과를 뿌리는 함수 
	pongSearch : function(z)
	{
	    var fullName = z.name1 + " " + z.name2 +" "+z.name3;
	    $("#address1").attr('value', z.name1);
	    $("#address2").attr('value', z.name2);
	    $("#address3").attr('value', z.name3);
	    map.related_news(z.name2);
	    $("#where").text(fullName);
	},
	// HTML태그 안 먹게 하는 함수
	escapeHtml : function(str) 
	{
	    str = str.replace(/&amp;/g, "&");
	    str = str.replace(/&lt;/g, "<");
	    str = str.replace(/&gt;/g, ">");
	    return str;
	},
	// HTML태그 삭제하는 함수
	stripHTMLtag : function(string) {
	    var objStrip = new RegExp();
	    objStrip = /[<][^>]*[>]/gi;
	    return string.replace(objStrip, "");
	},
	// 특정 좌표에 마커 추가
	addMark : function(lat, lng)
	{
	    var point = new DLatLng(lat, lng);
	    var mark = new DMark(point);
	    map.addOverlay(mark);
	    map.setCenter(point, 2);
	}
    };

var map =
    {
	mapObj: null,
	markers: [],
	news_log: null,
	init : function (qry) {
	    if (qry != "") {
		var encoded_qry = encodeURI(qry);
		$.getJSON("lib/geo_code_proxy.php?q=" + encoded_qry,
			  function(data) { 
			      if (typeof (data.error) == "undefined") {
				  map.mapObj = new DMap("map",
				      {
					  // point:new DLatLng("37.3218", "126.801"), // test
 					  point:new DLatLng(data.lat, data.lng),
					  width: "468px",

					  contextMenu: true,
					  reduced_scale: true,
					  map_type: "TYPE_SKYVIEW",
					  level:2
				      });
				  
				  $("#lat").attr('value', data.lat);
				  $("#lng").attr('value', data.lng);
				  
				  coord2addr.pingSearch(data.lat, data.lng);
				  				  
				  var zoom_ctrl = new DZoomControl();
				  var type_ctrl = new DMapTypeControl();
				  var center = map.mapObj.getCenter();
				  var info =
				    new DInfoWindow('여기에 보고할까요?<br/><input style="margin-top:10px;width:120px" onclick="$(\'#report-area\').show(\'blind\', {}, 500);" type="button" value="보고하기" />', {width:140, height:50});



				 //var info = new DInfoWindow('<input onclick="$(\'#report-area\').show(\'blind\', {}, 500);" type="button" value="보고하기" />');

				  var mark = new DMark(new DPoint(center.x, center.y),
						       {infowindow : info,
							draggable : true,
							clickable: false,
						        zindex : 100});

				  map.mapObj.addOverlay(mark);
				  map.mapObj.addControl(zoom_ctrl);
				  map.mapObj.addControl(type_ctrl);

				  zoom_ctrl.setValign("bottom");
				  
				  map.spreadMarker();
				  map.panoramio_image();

				  map.mapObj.enableDoubleClickZoom();

				  DEvent.addListener(map.mapObj, "dblclick", function(point) {
					  // map.mapObj.panTo(new DLatLng(point.x, point.y));
				  	  map.mapObj.zoomIn();
					  //map.mapObj.setCenter(point);
				      });

				  DEvent.addListener(map.mapObj, "zoom", map.spreadMarker);
				  DEvent.addListener(map.mapObj, "enddrag", map.spreadMarker);
				  DEvent.addListener(map.mapObj, "enddrag", map.panoramio_image);

				  DEvent.addListener(mark, "enddrag", function() {
				      var point = this.getPoint();
				      $('#lat').attr('value', point.y);
				      $('#lng').attr('value', point.x);
				      coord2addr.pingSearch(point.y, point.x);
				      info.show();
				      // $("#report-area").toggle("blind", {}, 500);
				  });
			      } else {
				  alert("지역을 찾을 수 없습니다.");
			      }
			  });
	    }
	},

	related_news : function(query) {
	    var qry = encodeURI(query);
	    if (query == map.news_log) {
		return;
	    }

	    map.news_log = query;
	    $("#news-list").empty();
	    $("#news-list").css('display','block');
	    $.getJSON("lib/naver_news_proxy.php?query=" + qry +
		      "&display=5",
		      function (data) {
			  $.each(data, function (i, item) {
			      var article = $("<div/>").addClass('news-article');

			      var title_link = $("<a/>").attr("href", item.link).html(coord2addr.stripHTMLtag(item.title)).css('color', 'blue');
			      var title = $("<h5/>");
			      title_link.appendTo(title);

			      var dt = Date.parse(item.pub_date);
			      var pdate = new Date(dt);

			      var year = pdate.getFullYear();
			      var month = Number(pdate.getMonth())+1;
			      var day = pdate.getUTCDate();

			      var h = pdate.getHours();
			      var hour = h < 10 ? "0" + h : h;
			      var min = pdate.getMinutes();
			      var sec = pdate.getSeconds();

			      var pub_date_str = year + "년 " + month + "월 " + day + "일 " +  hour + ":" + min;

			      var pub_date = $("<p/>").text(pub_date_str);
			      var desc = $("<div/>").html(coord2addr.stripHTMLtag(item.desc));
			      title.appendTo(article);
			      pub_date.appendTo(article);
			      desc.appendTo(article);
			      article.appendTo("#news-list");
			  });
		      });
	},

	panoramio_image : function() {
	    $("#photos").empty();
	    var boundary = map.mapObj.getBound();
	    $.getJSON("lib/panoramio_proxy.php?minx=" + boundary.left +
		      "&maxx=" + boundary.right +
		      "&miny=" + boundary.bottom +
		      "&maxy=" + boundary.top +
		      "&size=square",
		      function (data) {
			  var photos = data.photos;
			  var cssObj = {
			      'border': "1px solid gray",
			      'margin': "4px"
			  };

			  $.each(photos, function (i, item) {
			      var a = $("<a/>").attr('href', item.photo_url);
			      $("<img/>").attr('src', item.photo_file_url)
			      .css(cssObj).appendTo(a);
			      a.appendTo("#photos");
			  });
			  $("<div/>").css({
			      'float':'right',
			      'clear':'both',
			      'margin-bottom' : '10px'
				      }).html('Powered by <a href="http://panoramio.com">panoramio.com</a>').appendTo("#photos");

		      });
	},

	spreadMarker : function() {
	    // map.mapObj.clearOverlay();
	    var boundary = map.mapObj.getBound();
	    $.getJSON("lib/get_mark_within_bound.php?left=" + boundary.left + 
		      "&right="  + boundary.right +
		      "&bottom=" + boundary.bottom +
		      "&top="    + boundary.top ,
		      function (data) {
			  $("#near-list").empty();
			  $("#near-list").css('display', 'block');
			  $.each(data, function (i, item) {
			      var li = $("<li/>");
			      $("<a/>").attr('href', "view_report.php?id=" + item.id).text(item.subject).appendTo(li);
			      li.appendTo("#near-list");
      
			      if ( typeof (map.markers[item.id]) == 'undefined' ||
				   map.markers[item.id] == false) {
				  var mark = new DMark(new DPoint(item.lng, item.lat),
				      { draggable: false});
				  map.mapObj.addOverlay(mark);
				  map.markers[item.id] = true;

			      }
			  });
		      });
	}
    };

var list_reports =
    {
	init: function() {
	    $("#report-button").click (
		function() {
		    $("#report-area").toggle("blind", {}, 500);
		    return false;
		});
	}
    };

